package com.ypan.uninstall;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AppListAdapter extends BaseAdapter {
	private static final String TAG = "AppListAdapter";
	private LayoutInflater mInflater;
	private List<ApkInfo> mApkList;

	public AppListAdapter(LayoutInflater inflater, List<ApkInfo> apkList) {
		// Cache the LayoutInflate to avoid asking for a new one each time.
		mInflater = inflater;
		mApkList = apkList;
	}

	public void update(List<ApkInfo> apkList) {
		mApkList = apkList;
	}

	public int getCount() {
		// Log.v(TAG, "List Length = "+apkList.size());
		return mApkList.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public void updateDisplay() {
		notifyDataSetChanged();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list, null);
			holder = new ViewHolder();
			holder.TVappname = (TextView)convertView.findViewById(R.id.appname);
			holder.TVsize = (TextView)convertView.findViewById(R.id.size);
			holder.TVtime = (TextView)convertView.findViewById(R.id.time);
			holder.TVinfo = (TextView)convertView.findViewById(R.id.information);
			holder.icon = (ImageView) convertView.findViewById(R.id.icon);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		//set app name
		if(mApkList.get(position).version == null)
		{
			holder.TVappname.setText(mApkList.get(position).appName);
		}
		else {
			holder.TVappname.setText(mApkList.get(position).appName+" "+mApkList.get(position).version);
		}
		//set time
		holder.TVtime.setText(new Date(mApkList.get(position).modifiedTime).toLocaleString());
		//set size
		long size = mApkList.get(position).apkSize;
		DecimalFormat df = new DecimalFormat("0.00");
		if(size < 1000*1024)
		{
			float temp =(float) ((float) size/1024.0);
			holder.TVsize.setText(df.format(temp)+"KB");
		}
		else 
		{
			float temp =(float) ((float) size/(1024.0*1024.0));
			holder.TVsize.setText(df.format(temp)+"MB");
		}
		holder.TVinfo.setText("");
		Bitmap appIcon = mApkList.get(position).icon;
		holder.icon.setImageBitmap(appIcon);
		return convertView;
	}

	static class ViewHolder {
		TextView TVappname;
		TextView TVtime;
		TextView TVsize;
		TextView TVinfo;
		ImageView icon;
	}
}